package auth_ctrl

import (
	"admin-system/internal/request"
	"admin-system/internal/service/auth_svc"
	"admin-system/internal/util"
	"admin-system/pkg/error_code"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
	"strconv"
)

type AdminUserController struct {
	AdminService *auth_svc.AdminService
}

func NewAdminUserController(AdminService *auth_svc.AdminService) *AdminUserController {
	return &AdminUserController{
		AdminService: AdminService,
	}
}

// Login 处理用户登录
func (a *AdminUserController) Login(c *gin.Context) {
	var req request.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "无效的请求参数")
		return
	}
	// 查询用户
	admin, err := a.AdminService.Login(c, req)
	if err != nil {
		response.Fail(c, error_code.ErrLoginFailed, "登录失败")
		return
	}

	// 生成 token
	token, err := util.GenerateToken(admin.ID, admin.RoleID, admin.Username)
	if err != nil {
		response.Fail(c, error_code.ErrTokenGenFailed, "Token生成失败")
		return
	}

	// 返回请求
	response.Success(c, gin.H{
		"code":     0,
		"msg":      "success",
		"token":    token,
		"id":       admin.ID,
		"username": admin.Username,
		"email":    admin.Email,
	})
}

// 刷新token
func (a *AdminUserController) RefreshToken(c *gin.Context) {
	// 获取请求中的 token
	tokenString := c.Request.Header.Get("Authorization")[7:]
	token, err := util.RefreshExpTime(tokenString)
	if err != nil {
		response.Fail(c, error_code.ErrTokenInvalid, "token已过期请重新登录")
		return
	}
	response.Success(c, gin.H{"token": token})
	return
}

// 新增管理员
func (a *AdminUserController) CreateAdminUser(c *gin.Context) {
	// 绑定表单
	var req request.CreateAdminUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "请求参数错误"+err.Error())
		return
	}

	admin, err := a.AdminService.CreateAdminUser(c, req)
	if err != nil {
		response.Fail(c, error_code.ErrInternalServer, "管理员不存在"+err.Error())
		return
	}
	response.Success(c, admin)
	return
}

// GetUserInfo
// @Summary 获取用户信息
func (a *AdminUserController) GetUserInfo(c *gin.Context) {
	// 获取请求参数
	userIdStr, ok := c.Params.Get("id")
	if !ok {
		response.Fail(c, error_code.ErrInvalidParams, "参数错误")
		return
	}
	userId, err := strconv.ParseInt(userIdStr, 10, 64)
	if err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "参数错误")
		return
	}
	// 通过用户id 获取用户信息
	admin, err := a.AdminService.GetUserInfoByID(c, userId)
	if err != nil {
		response.Fail(c, error_code.ErrUserNotExists, "用户不存在")
	}
	if admin == nil {
		response.Fail(c, error_code.ErrUserNotExists, "用户不存在")
		return
	}
	response.Success(c, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"id":       admin.ID,
			"username": admin.Username,
			"email":    admin.Email,
			"role_id":  admin.RoleID,
			"nickname": admin.Nickname,
			"avatar":   admin.Avatar,
			"mobile":   admin.Mobile,
		},
	})
	return
}
